package com.xiaoyy.app.extend.gateway.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayMarketingCampaignDrawcampTriggerRequest;
import com.alipay.api.response.AlipayMarketingCampaignDrawcampTriggerResponse;
import com.xiaoyy.app.extend.common.enums.AppApiEnum;
import com.xiaoyy.app.extend.common.vo.VouchersIssuanceVO;
import com.xiaoyy.app.extend.gateway.req.AlipayLoginReq;
import com.xiaoyy.app.extend.gateway.req.VouchersIssuanceReq;
import com.xiaoyy.app.extend.gateway.validators.LoginValidators;
import com.xiaoyy.app.extend.util.AlipayUtil;
import com.xiaoyy.core.common.enums.LoginTypeEnum;
import com.xiaoyy.core.common.exception.AppException;
import com.xiaoyy.core.common.vo.AppResponse;
import com.xiaoyy.core.common.vo.LoginVO;
import com.xiaoyy.core.common.vo.TokenVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;

/**
 * 支付宝用户登入相关
 *
 * @author chenzh
 * @date 2018-08-17
 */
@RestController
@RequestMapping(value = "/other/sso/alipay")
@Api(tags = "第三方支付宝登录管理")
public class AlipayLoginController {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Value("${system.config.alipay.app.url}")
    private String appUrl;
    /**
     * 用户登入
     */
    @PostMapping(value = "/login/alipay", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "支付宝登录", notes = "用户登录")
    public AppResponse<TokenVO> loginAlipay(@RequestBody @Validated(value = {LoginValidators.ToLogin.class}) AlipayLoginReq loginReq, @ApiIgnore HttpServletRequest request) {
        LoginVO loginVO=(LoginVO)Convert.convert(LoginVO.class, loginReq);
        loginVO.setLoginKey(loginReq.getCode());

        //登录前校验
        if (StringUtils.isBlank(loginVO.getLoginKey())) {
            throw new AppException("登录唯一码authCode不能为空！");
        }
        //登录类型
        if (StringUtils.isBlank(loginVO.getLoginType())){
            loginVO.setLoginType(LoginTypeEnum.alipay.getType());
        }else if(!LoginTypeEnum.alipay.getType().equalsIgnoreCase(loginVO.getLoginType())){
            throw new AppException("登录类型错误！");
        }

        loginVO=AlipayUtil.getAlipayInfo(loginVO);

        try {
            String body = HttpUtil.post(appUrl + AppApiEnum.ALIPAYLOGIN.getType(), JSON.toJSONString(loginVO));
            return JSON.parseObject(body, AppResponse.class);
        }catch (Exception e){
            return AppResponse.errorMsg("内部服务请求异常");
        }
    }


    /**
     * 消费券发放
     */
    @PostMapping(value = "/issue", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "消费券发放", notes = "补贴发放")
    public AppResponse<VouchersIssuanceVO> VouchersIssue(@RequestBody VouchersIssuanceReq viReq) {
        VouchersIssuanceVO vivo=new VouchersIssuanceVO();
        AlipayClient alipayClient=AlipayUtil.getAlipayClient();
        try {
            AlipayMarketingCampaignDrawcampTriggerRequest request = new AlipayMarketingCampaignDrawcampTriggerRequest();
            String reqjson = JSONObject.toJSONString(viReq);
            request.setBizContent(reqjson);
            AlipayMarketingCampaignDrawcampTriggerResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                vivo=(VouchersIssuanceVO) Convert.convert(VouchersIssuanceVO.class, response);
                System.out.println("调用成功");
            } else {
                return AppResponse.error(-1,"调用失败:"+response.getSubMsg());
            }
        }catch(Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.toString());
            return AppResponse.error(-1,"发券接口出现错误");
        }
        return AppResponse.successData(vivo);
    }


}
